package com.party.jackclientandroid.ui_order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.party.jackclientandroid.R;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.OrderService;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.BaseFragment;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.Order;
import com.party.jackclientandroid.loadviewhelper.help.OnLoadViewListener;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.utils.CommonUtil;
import com.party.jackclientandroid.utils.ConstUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 订单-我的拼团
 * 订单-其他订单
 */
public class OrderStateFragment extends BaseFragment {
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refresh_layout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    private int page = 1;
    private int statusId = 0;
    private OrderService orderService;
    private List<Order> dataList = new ArrayList<>();
    private int type;
    CommonAdapter<Order> commonAdapter;

    public static OrderStateFragment newInstance(int statusId) {
        OrderStateFragment fragment = new OrderStateFragment();
        Bundle args = new Bundle();
        args.putInt("statusId", statusId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void receiveBundleFromActivity(Bundle arg) {
        statusId = arg.getInt("statusId");
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_order_state;
    }

    @Override
    protected void initData() {
        orderService = new OrderService((BaseActivity) mActivity);
        helper = new LoadViewHelper(refresh_layout);
        helper.setListener(new OnLoadViewListener() {
            @Override
            public void onRetryClick() {
                loadData();
            }
        });
        helper.showLoading();
        loadData();
    }

    @Override
    protected void initView() {
        super.initView();
        refresh_layout.setEnableFooterFollowWhenLoadFinished(true);
        commonAdapter = new CommonAdapter<Order>(mActivity, R.layout.item_order, dataList) {
            @Override
            protected void convert(ViewHolder viewHolder, Order order, int position) {
                viewHolder.setText(R.id.shop_name_tv, order.getItemName() + "");
                viewHolder.setText(R.id.num_tv, "数量：" + order.getNum());
                viewHolder.setText(R.id.final_price_tv, "总价：¥" + order.getFinalPrice());
                viewHolder.setText(R.id.time_tv, "下单时间：" + CommonUtil.formatTime(order.getCreate()));
                TextView status_tv = viewHolder.getView(R.id.status_tv);
                viewHolder.setText(R.id.status_tv, getOrderStateNameByOrderStateId(order.getOrderState(), status_tv));
                ImageView shopImageIv = viewHolder.getView(R.id.home_image);
                mApplication.getImageLoaderFactory().loadCommonImgByUrl(mFragment, order.getImgUrl(), shopImageIv);
                type = order.getType();
                ImageView ivOrderCoupon;
                if (type == 1) {
                    ivOrderCoupon = viewHolder.getView(R.id.iv_order_coupon);
                    ivOrderCoupon.setBackgroundResource(R.mipmap.dai);
                } else if (type == 2) {
                    ivOrderCoupon = viewHolder.getView(R.id.iv_order_coupon);
                    ivOrderCoupon.setBackgroundResource(R.mipmap.group_buy);
                } else if (type == 5) {
                    ivOrderCoupon = viewHolder.getView(R.id.iv_order_coupon);
                    ivOrderCoupon.setBackgroundResource(R.mipmap.ping);
                } else if (type == 6) {
                    ivOrderCoupon = viewHolder.getView(R.id.iv_order_coupon);
                    ivOrderCoupon.setBackgroundResource(R.mipmap.miao);
                }
            }
        };
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(mActivity, R.drawable.layout_divider_item_decoration));
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(commonAdapter);
    }

    @Override
    protected void initListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                goToWhereByState(dataList.get(position));
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        refresh_layout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
    }

    public void loadData() {
        page = 1;
        addDisposableIoMain(orderService.getUserOrderList(statusId, page), new DefaultConsumer<List<Order>>(mApplication) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                helper.showError();
            }

            @Override
            public void operateSuccess(BaseResult<List<Order>> baseBean) {
                List<Order> data = baseBean.getData();
                dataList.clear();
                if (data != null && data.size() > 0) {
                    dataList.addAll(data);
                    helper.showContent();
                } else {
                    helper.showEmpty();
                }
                commonAdapter.notifyDataSetChanged();
                refresh_layout.finishRefresh();
            }
        });
    }

    private void loadMoreData() {
        page++;
        addDisposableIoMain(orderService.getUserOrderList(page, statusId), new DefaultConsumer<List<Order>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<Order>> baseBean) {
                List<Order> data = baseBean.getData();
                boolean noMoreData = false;
                if (data != null && data.size() > 0) {
                    dataList.addAll(data);
                    if (data.size() <= ConstUtils.PAGE_SIZE) {
                        noMoreData = true;
                    }
                } else {
                    noMoreData = true;
                }
                commonAdapter.notifyDataSetChanged();
                // 没有更多数据了
                if (noMoreData) {
                    refresh_layout.finishLoadMoreWithNoMoreData();
                } else {
                    refresh_layout.finishLoadMore();
                }
            }
        });
    }

    public void goToWhereByState(Order order) {
        int orderStateId = order.getOrderState();
        String orderId = order.getId() + "";
        Intent intent;
        switch (orderStateId) {
            case Constant.ORDER_STATE_WAIT_PAY:
                intent = new Intent(mActivity, OrderDetailRePayActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_WAIT_USE:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_WAIT_COMMENT:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_FINISHED:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_CANCELED:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_REFUNDING:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_REFUNDED:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_ING:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_SUCCESS:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_FAILED:
                intent = new Intent(mActivity, OrderDetailWaitUseActivity.class);
                intent.putExtra("order_id", orderId);
                startActivity(intent);
                break;
        }
    }

    public String getOrderStateNameByOrderStateId(int orderStateId, TextView status_tv) {
        String orderStateName = null;
        switch (orderStateId) {
            case Constant.ORDER_STATE_WAIT_PAY:
                orderStateName = "待付款";
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                break;
            case Constant.ORDER_STATE_WAIT_USE:
                status_tv.setTextColor(getResources().getColor(R.color.red));
                orderStateName = "待使用";
                break;
            case Constant.ORDER_STATE_WAIT_COMMENT:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "待评价";
                break;
            case Constant.ORDER_STATE_FINISHED:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "已完成";
                break;
            case Constant.ORDER_STATE_CANCELED:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "已取消";
                break;
            case Constant.ORDER_STATE_REFUNDING:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "退款中";
                break;
            case Constant.ORDER_STATE_REFUNDED:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "退款完成";
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_ING:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "拼团中";
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_SUCCESS:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "拼团成功";
                break;
            case Constant.ORDER_STATE_SPELLING_GROUP_FAILED:
                status_tv.setTextColor(getResources().getColor(R.color.gray));
                orderStateName = "拼团失败";
                break;
            default:
                orderStateName = "";
                break;
        }
        return orderStateName;
    }
}
